package ArrayList.work05;
import javax.management.RuntimeErrorException;

public class MyArrayList <E>{
    private Object[] elementDate;//泛型存放数组
    private int size;//长度

    private static final int DEFALT_CAPACITY=10;//默认容量
    public MyArrayList() {


        elementDate=new Object[DEFALT_CAPACITY];//开辟默认大小数组

    }
    public MyArrayList(int capacity) {


        if(capacity<0) {


            throw new RuntimeException( "容量不能为负数");
        }else if(capacity==0) {


            elementDate=new Object[DEFALT_CAPACITY];
        }else {


            elementDate=new Object[capacity];
        }//自定义大小

    }
    public void add(E obj) {


        //扩容操作
        if(size==elementDate.length) {


            Object[] newArray=new Object[(int) (elementDate.length+elementDate.length*0.5)];
            //增加为原来的1.5倍
            System.arraycopy(elementDate, 0, newArray, 0, elementDate.length);
            elementDate=newArray;
        }
        elementDate[size++]=obj;
    }
    @Override
    public String toString() {


        //格式化输出
        StringBuilder sb=new StringBuilder();
        sb.append("[");
        for(int i=0;i<size;i++) {


            if(i!=0) {


                sb.append(",");
            }
            sb.append(elementDate[i]);
        }
        sb.append("]");
        return sb.toString();
    }
    public E get(int index) {


        //get方法
        checkRange(index);
        return (E) elementDate[index];
    }
    public void set(E element,int index) {


        checkRange(index);
        elementDate[index]=element;
    }
    public void checkRange(int index) {


        if(index<0||index>size-1) {


            //下标不合法
            throw new RuntimeException("输入下标不合法");
        }
    }
    public void remove(E element) {


        //通过元素删除元素
        for(int i=0;i<size;i++) {


            if(element.equals(elementDate[i])) {


                remove(i);
            }
        }
    }
    public void remove(int index) {


        //通过下标删除
        checkRange(index);
        for(int i=index;i<size-1;i++) {


            elementDate[i]=elementDate[i+1];
        }
        size--;
    }
    public int size() {


        return size;
    }
    public boolean isEmpty() {


        return size==0?true:false;
    }
    public static void main(String[] args) {


        MyArrayList ma=new MyArrayList(20);
        ma.add("1234");
        ma.add("1234");
        ma.add("1234");
        ma.add("1234");
        ma.add("1234");
        ma.set("haha", 2);
        ma.remove(10);
        System.out.println(ma);
    }
}
